package middleware

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func RecoverWithLog(log *zap.Logger) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		defer func() {
			if err := recover(); err != nil {
				//httpRequest, _ := httputil.DumpRequest(ctx.Request, false)
				//headers := strings.Split(string(httpRequest), "\r\n")
				log.DPanic(
					fmt.Sprintf("gin recover from panic: %v", err),
					zap.Any("error", err),
					//zap.Any("request", headers),
					zap.String("uri", ctx.Request.RequestURI),
					zap.String("method", ctx.Request.Method),
					zap.String("client_ip", ctx.ClientIP()),
				)
				ctx.AbortWithStatus(http.StatusInternalServerError)
			}
		}()
		ctx.Next()
	}
}
